package com.zzzzzz.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zzzzzz.account.ShiroDbRealm;

@Configuration
public class SecurityConfig {
	
	@Bean
	public Realm configureRealm() {
		return new ShiroDbRealm();
	}
	
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager configSecurityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(configureRealm());
		return securityManager;
	}
	
	@Bean(name = "lifecycleBeanPostProcessor")
	public LifecycleBeanPostProcessor configLifecycleBeanPostProcessor() {
		LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();
		return lifecycleBeanPostProcessor;
	}
	
	@Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean configShiroFilterFactoryBean() {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(configSecurityManager());
		shiroFilterFactoryBean.setLoginUrl("/login");
		shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
		Map<String, javax.servlet.Filter> filters = new HashMap<String, javax.servlet.Filter>();
		filters.put("authc", new PassThruAuthenticationFilter());
		shiroFilterFactoryBean.setFilters(filters);
		shiroFilterFactoryBean.setFilterChainDefinitions("/control_panel/** = roles[administrator]");
		return shiroFilterFactoryBean;
	}
}
